﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Ninject;
using System.Windows.Forms;
using WeifenLuo.WinFormsUI.Docking;
using System.Collections;
using System.Reflection;

namespace eBook.WinApp
{
  public class FormFactory
  {
    private static FormFactory _factory;

    public static FormFactory Instance
    {
      get 
      {
        if (_factory == null)
          _factory = new FormFactory();

        return _factory; 
      }
    }

    private IKernel _kernel;
    public frmMain MdiContainer{get; set;}
    public Action<DockContent> ShowDockContent { get; set; }

    public FormFactory()
    {
      this.CreateKernel();
    }

    private void CreateKernel()
    {
      _kernel = new StandardKernel();
      string[] modules = new string[2] { "eBook.EFRepositories.dll", "eBook.Services.dll" };
      _kernel.Load( modules );
      
    }

    public DockContent LaunchDockContent<T>(bool allowMultipleInstance = false)
    {
      if ( typeof(T).BaseType != typeof(DockContent) )
        throw new Exception("Error launching provided type because it is not a DockContent");

      //if (this.ShowDockContent == null)
      //  throw new Exception("Unable to show DockContent. Action declaration is null.");

      DockContent formInstance = null;
      if (!allowMultipleInstance && this.MdiContainer != null)
        formInstance = this.MdiContainer.MdiChildren.FirstOrDefault(x => x.GetType() == typeof(T)) as DockContent;

      if (formInstance == null)
        formInstance = _kernel.Get<T>() as DockContent;

      if (this.ShowDockContent != null)
        this.ShowDockContent(formInstance);

      return formInstance;
    }



  }



}
